import React, { useEffect, useState } from 'react';
import moment from 'moment';
import { useModel, connect, history } from 'umi';
import { ConfigProvider, Modal, Button, Form, Input, message } from 'antd';
import { AliveScope } from 'react-activation';
import { SettingDrawer } from '@ant-design/pro-layout';
import SystemHeader from '@/components/SystemHeader';
import SystemMenu from '@/components/SystemMenu';
import SystemFooter from '@/components/SystemFooter';
import DebounceWrapper from '@/components/DebounceWrapper';
import { initDefaultPassword } from '@/services/user';
import { setTheme } from '@/utils/auth';
import styles from './index.less';
import zhCN from 'antd/lib/locale/zh_CN';
import 'moment/locale/zh-cn';

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
moment.locale('zh-cn');
const DebounceButton = DebounceWrapper(Button);

const PasswordInit = ({ visible, closeModal }) => {
  const [form] = Form.useForm();
  const [actionLoading, setActionLoading] = useState(false);

  const handleCancel = () => {
    if (!actionLoading) {
      if (!REACT_APP_DEFAULT_SETTING_PASSWORD) {
        closeModal();
      } else {
        message.warning('请先更新设置登录密码');
      }
    }
  };

  const handleConfirm = () => {
    form.validateFields().then((values) => {
      setActionLoading(true);
      initDefaultPassword(values)
        .then(() => {
          closeModal();
          setActionLoading(false);
          message.success('密码设置成功');
        })
        .catch(() => {
          setActionLoading(false);
        });
    });
  };

  return (
    <Modal
      visible={visible}
      maskClosable={false}
      title={
        <div className={styles.defaultPasswordTitle}>
          设置账号登录密码
          <div className={styles.defaultPasswordSubTitle}>
            您的登录密码为初始密码，为了保障您的安全，请在当前窗口修改密码
          </div>
        </div>
      }
      onCancel={handleCancel}
      footer={[
        <DebounceButton
          key="confirm"
          type="primary"
          loading={actionLoading}
          onClick={handleConfirm}
        >
          提交
        </DebounceButton>,
      ]}
    >
      <Form {...layout} form={form} name={'reset-default-password'}>
        <Form.Item
          name="newPass"
          label={'新密码'}
          validateTrigger={['onChange', 'onBlur']}
          rules={[
            { required: true, message: '请输入新密码' },
            {
              validateTrigger: 'onBlur',
              validator: (rule, val) => {
                if (val) {
                  if (
                    /^(?![0-9]+$)(?![a-zA-Z]+$)(?!([^(0-9a-zA-Z)]|[])+$)([^(0-9a-zA-Z)]|[]|[a-zA-Z]|[0-9]){6,}$/.test(
                      val,
                    )
                  ) {
                    return Promise.resolve();
                  } else {
                    return Promise.reject(
                      new Error(
                        '必须是6～20个英文字母、数字或符合，且字母、数字、符号至少包含两种',
                      ),
                    );
                  }
                } else {
                  return Promise.resolve();
                }
              },
            },
          ]}
        >
          <Input.Password placeholder="请输入新密码" maxLength={20} autoComplete="off" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default connect(
  ({ global, user }) => ({
    collapsed: global.collapsed,
    isDefaultPassword: user.isDefaultPassword,
  }),
  (dispatch) => ({
    updateThemeStatus: (payload) => dispatch({ type: 'global/updateThemeStatus', payload }),
    initRouteOpts: (payload) => dispatch({ type: 'menu/initRouteOption', payload }),
    closeInitPasswordModal: () => dispatch({ type: 'user/updatePasswordStatus', payload: false }),
  }),
)(
  ({
    collapsed,
    isDefaultPassword,
    updateThemeStatus,
    initRouteOpts,
    closeInitPasswordModal,
    children,
  }) => {
    const { initialState, setInitialState } = useModel('@@initialState');
    const { settings, menuData, defaultUrl, routePathList } = initialState;

    // 主题切换
    const updateThemeSetting = (settings) => {
      const { navTheme, primaryColor, menuRender, headerRender, footerRender } = settings || {};
      const isDark = navTheme === 'realDark';
      setTheme(
        _.pickBy(
          settings || {},
          (v, k) => !_.includes(['headerRender', 'menuRender', 'footerRender', 'collapsed'], k),
        ),
      );
      updateThemeStatus({ isDark, primaryColor });
      setInitialState({
        ...initialState,
        settings: _.assign({}, settings, {
          headerRender: headerRender !== false ? (props) => <SystemHeader {...props} /> : false,
          menuRender: menuRender !== false ? (props) => <SystemMenu {...props} /> : false,
          footerRender: footerRender !== false ? (props) => <SystemFooter {...props} /> : false,
        }),
      });
    };

    // 初始化或更新路由管理数据
    useEffect(() => {
      if (menuData && menuData.length) {
        initRouteOpts({ defaultUrl, routePathList, currentPath: history.location.pathname });
      }
    }, [menuData]);

    // 更新collapsed
    useEffect(() => {
      setInitialState({ ...initialState, settings: _.assign({}, settings, { collapsed }) });
    }, [collapsed]);

    return (
      <ConfigProvider locale={zhCN}>
        <div
          className={
            settings.menuRender !== false && collapsed ? 'system-with-menu-render-collapsed' : null
          }
        >
          <AliveScope>{children}</AliveScope>
          <PasswordInit visible={isDefaultPassword} closeModal={closeInitPasswordModal} />
        </div>
        <SettingDrawer
          hideHintAlert
          hideCopyButton
          disableUrlParams
          enableDarkTheme
          settings={settings}
          onSettingChange={updateThemeSetting}
          getContainer={() => document.getElementById('root')}
        />
      </ConfigProvider>
    );
  },
);
